#include <jni.h>
#include <string>
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>

#include <stdlib.h>
#include <unistd.h>

extern "C"{

// 我的c库
#include "dai_log.h"

}


extern "C" JNIEXPORT jstring JNICALL
Java_com_dai_helloc_MainActivity_stringFromJNI(
        JNIEnv* env,
        jobject /* this */) {

    // 里面写一些代码
    dai_log("hello world! My age is:%d",18);
    dai_log("This IS A LOG! name:%s","zhangsan");

    dai_log("dai-sqrt:%f",dai_sqrt(144.f));

    std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());
}

extern "C"
JNIEXPORT jstring JNICALL
Java_com_dai_helloc_MainActivity_loadAssetFromJNI(JNIEnv *env, jobject thiz, jobject am) {
     AAssetManager *mgr = AAssetManager_fromJava(env,am);
     if (mgr == NULL){
         dai_log("mgr is null!");
         return env->NewStringUTF("");
     }
     AAsset *asset = AAssetManager_open(mgr,"xxx.txt",AASSET_MODE_UNKNOWN);
     if (asset == NULL){
         dai_log("asset not found!");
         return env->NewStringUTF("");
     }
     long size = AAsset_getLength(asset);
     char *buf = (char *)malloc(sizeof(char )*(size + 1));
     buf[size] = '\0';
    AAsset_read(asset,buf,size);
    dai_log("读到的内容为:%s",buf);
    free(buf);
    AAsset_close(asset);
    return env->NewStringUTF("");
}

// 启动一个进程
extern "C"
JNIEXPORT void JNICALL
Java_com_dai_helloc_MainActivity_startNewProcessFromJNI(JNIEnv *env, jobject thiz) {
    dai_fork();
}


// 启动一个孤儿进程
extern "C"
JNIEXPORT void JNICALL
Java_com_dai_helloc_EntryService_startOrphanProcess(JNIEnv *env, jobject thiz,jstring filePath1) {
    dai_log("当前进程pid:%ld",getpid());

    char *indicator_self_path = (char *) env->GetStringUTFChars(filePath1, 0);
    dai_log("文件路径为:%s",indicator_self_path);

    pid_t  pid1 = fork();
    if (pid1 < 0){
        dai_log("生成p1 进程失败!");
        exit(1);
    }else if (pid1 == 0){
        dai_log("我是p1 进程.我的 pid:%ld",getpid());
        p1_do(indicator_self_path);
    }else{
        pid_t  pid2 = fork();
        if (pid2 < 0){
            dai_log("生成p2 进程失败!");
            exit(1);
        }else if(pid2 == 0){
            dai_log("我是p2 进程,我的 pid:%ld",getpid());
            p2_do(indicator_self_path);
        }else{

        }
    }
}extern "C"
JNIEXPORT void JNICALL
Java_com_dai_helloc_EntryService_startXX(JNIEnv *env, jobject thiz) {
    // 直接搞一个孤儿进程
    pid_t  pid = fork();
    if (pid < 0){
        dai_log("生成 mid 进程失败!");
        exit(1);
    }else if(pid == 0){
        dai_log("生成 mid 进程成功! .mid 进程 pid:%ld",getpid());
        pid = fork();
        if (pid < 0){
            dai_log("生成 孤儿 进程失败!");
            exit(1);
        }else if(pid == 0){
            dai_log("生成  孤儿 进程成功! .孤儿 进程 pid:%ld",getpid());
            int geCounter = 0;
            while (1){
                sleep(2);
                geCounter++;
                dai_log("geCounter:%d",geCounter);
            }
        }else{
            // 托孤
            exit(0);
        }
    }
}